<template>
  <a-spin :spinning='confirmLoading'>
    <a-tabs defaultActiveKey='1'>
      <a-tab-pane tab='1、基本信息' key='1'></a-tab-pane>
    </a-tabs>
    <j-form-container :disabled='formDisabled'>
      <!-- 主表单区域 -->
      <a-form :form='form' slot='detail'>
        <a-row>
          <a-col :span='8'>
            <a-form-item label='合同编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['num', validatorRules.num]"
                :disabled="classifyShowInput != 'busSales'"
                placeholder='系统自动生成'
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='采购类型' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-dict-select-tag
                type='list'
                v-decorator="['type', validatorRules.type]"
                :trigger-change='true'
                dictCode='icm_contract_purchase_type'
                placeholder='请选择采购类型'
                :disabled="model.bpmStatus == '3'"
                @change='typeChange'
              />
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='合同名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['name', validatorRules.name]"
                placeholder='请输入合同名称'
                :disabled="model.bpmStatus == '3'"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='合同金额' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['money', validatorRules.money]"
                placeholder='请输入合同金额'
                style='width: 100%'
                :min='0'
                type='number'
                :disabled="model.bpmStatus == '3'"
              >
                <span slot='addonAfter'>元</span>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='项目名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['projectName', validatorRules.projectName]"
                :trigger-change='true'
                org-fields='id,name,code,charger,customer_name'
                dest-fields='projectId,projectName,projectCode,charger,customerName'
                code='pm_project_select'
                @callback='popupCallback'
                :disabled="model.bpmStatus == '3'"
              />
              <a-input v-decorator="['projectId']" v-show='false'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='项目经理' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-select-user-by-dep
                :multi='false'
                v-decorator="['charger', validatorRules.charger]"
                :disabled="model.bpmStatus == '3'"
              />
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='项目编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['projectCode']" disabled placeholder='请选择'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='客户简称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['customerName']" disabled placeholder='请选择'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='付款方式' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['paymentMethod', validatorRules.paymentMethod]"
                placeholder='请输入付款方式'
                :disabled="model.bpmStatus == '3'"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :span='8'>
            <a-form-item label='保质期' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input
                v-decorator="['qualityGuaranteePeriod', validatorRules.qualityGuaranteePeriod]"
                placeholder='请输入保质期'
                :disabled="model.bpmStatus == '3'"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :span='8'>
            <a-form-item label='供应商名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['supplierName']"
                :trigger-change='true'
                org-fields='id,name'
                dest-fields='supplierId,supplierName'
                code='contract_supplier_select'
                @callback='popupCallback'
                :disabled="model.bpmStatus == '3'"
              />
              <a-input v-decorator="['supplierId']" v-show='false'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='销售合同名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['saleName', validatorRules.saleName]"
                :trigger-change='true'
                org-fields='id,project_name,num,salesman,bid_project_id'
                dest-fields='saleId,saleName,saleNum,salesman,bidProjectId'
                code='contract_sale_select'
                @callback='saleNamePopupCallback'
                :disabled="model.bpmStatus == '3'"
              />
              <a-input v-decorator="['saleId']" v-show='false'></a-input>
              <a-input v-decorator="['bidProjectId']" v-show='false'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='销售合同编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['saleNum']" disabled placeholder='请选择'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='销售经理' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['salesman']" disabled placeholder='请选择'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='8'>
            <a-form-item label='附件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-upload
                v-decorator="['accessories', validatorRules.accessories]"
                :trigger-change='true'
                :disabled="model.bpmStatus == '3'"
              ></j-upload>
            </a-form-item>
          </a-col>
          <a-col :span='24'>
            <a-form-item label='备注' :labelCol='labelCol2' :wrapperCol='wrapperCol2'>
              <a-textarea
                v-decorator="['remarks']"
                rows='4'
                placeholder='请输入备注'
                :disabled="model.bpmStatus == '3'"
              />
            </a-form-item>
          </a-col>
          <div v-if="model.archived == 'N' && model.bpmStatus === '3'">
            <div v-has="'ContractSale:archive'">
              <a-col :span='8'>
                <a-form-item label='签订日期' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                  <j-date
                    placeholder='请选择签订日期'
                    v-decorator="['signDate', validatorRules.signDate]"
                    :trigger-change='true'
                    style='width: 100%'
                  />
                </a-form-item>
              </a-col>
              <a-col :span='8'>
                <a-form-item label='是否归档' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                  <j-switch v-decorator="['archived', validatorRules.archived]"></j-switch>
                </a-form-item>
              </a-col>
              <a-col :span='8'>
                <a-form-item label='归档文件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                  <j-upload v-decorator="['archiveFile', validatorRules.archiveFile]" :trigger-change='true'></j-upload>
                </a-form-item>
              </a-col>
            </div>
          </div>
          <div v-else-if="model.bpmStatus === '3' && model.archived == 'Y'">
            <a-col :span='8'>
              <a-form-item label='签订日期' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                <j-date
                  placeholder='请选择签订日期'
                  v-decorator="['signDate', validatorRules.signDate]"
                  :trigger-change='true'
                  style='width: 100%'
                />
              </a-form-item>
            </a-col>
            <a-col :span='8'>
              <a-form-item label='是否归档' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                <j-switch v-decorator="['archived', validatorRules.archived]"></j-switch>
              </a-form-item>
            </a-col>
            <a-col :span='8'>
              <a-form-item label='归档文件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
                <j-upload v-decorator="['archiveFile', validatorRules.archiveFile]" :trigger-change='true'></j-upload>
              </a-form-item>
            </a-col>
          </div>
        </a-row>
      </a-form>
    </j-form-container>

    <!-- 子表单区域 -->
    <a-tabs v-model='activeKey' @change='handleChangeTabs'>
      <a-tab-pane tab='2、付款计划' :key='refKeys[0]' :forceRender='true'>
        <j-editable-table
          :ref='refKeys[0]'
          :loading='contractPurchasePaymentTable.loading'
          :columns='contractPurchasePaymentTable.columns[type]'
          :dataSource='contractPurchasePaymentTable.dataSource'
          :maxHeight='300'
          :disabled="formDisabled || model.bpmStatus == '3'"
          :rowNumber='true'
          :rowSelection='true'
          :actionButton='true'
        >
          <template v-slot:payCondition='props'>
            <a-popover v-if='props.text && model.id && formDisabled' :content='props.text'>
              <div>
                <a-input
                  :value='props.text'
                  :disabled='formDisabled'
                  @change='(e) => payConditionInputchange(e, props)'
                ></a-input>
              </div>
            </a-popover>
            <a-input
              :value='props.text'
              :disabled='formDisabled'
              @change='(e) => payConditionInputchange(e, props)'
              v-else
            ></a-input>
          </template>
        </j-editable-table>
      </a-tab-pane>
    </a-tabs>
    <ContractBidProjectDetailList
      :mainId='bidProjectId || model.bidProjectId'
      :index='3'
      v-if='model.saleId || saleId'
    ></ContractBidProjectDetailList>
    <ContractSalePurchaseApplyDetailModal
      :mainId='saleId || model.saleId'
      v-if='model.saleId || saleId'
      :index='4'
    ></ContractSalePurchaseApplyDetailModal>
    <a-row v-if='showFlowSubmitButton' style='text-align: center; width: 100%; margin-top: 16px'>
      <a-button @click='handleOk' type='primary'>提 交</a-button>
    </a-row>
  </a-spin>
</template>

<script>
import pick from 'lodash.pick'
import { getAction, httpAction } from '@/api/manage'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import ContractBidProjectDetailList from './ContractBidProjectDetailList'
import ContractSalePurchaseApplyDetailModal from './ContractSalePurchaseApplyDetailModal'

export default {
  name: 'ContractPurchaseForm',
  mixins: [JEditableTableMixin],
  components: { ContractBidProjectDetailList, ContractSalePurchaseApplyDetailModal },
  data() {
    return {
      saleId: '',
      bidProjectId: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 22 }
      },
      type:1,//1=>add,2=>edit
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        supplierName: {
          rules: [{ required: true, message: '请输入供应商名称!' }]
        },
        projectName: {
          rules: [{ required: true, message: '请输入项目名称!' }]
        },
        salesman: {
          rules: [{ required: true, message: '请选择项目经理!' }]
        },
        saleName: {
          rules: [{ required: false, message: '请输入销售合同名称!' }]
        },
        type: {
          rules: [{ required: true, message: '请输入采购类型!' }]
        },
        name: {
          rules: [{ required: true, message: '请输入合同名称!' }]
        },
        paymentMethod: {
          rules: [{ required: true, message: '请输入付款方式!' }]
        },
        money: {
          rules: [
            { required: true, message: '请输入合同金额!' },
            { pattern: /^(([0-9]*)|([0]\.\d{0,4}|[0-9]*\.\d{0,4}))$/, message: '请输入正确的金额!' }
          ]
        },
        qualityGuaranteePeriod: {
          rules: [{ required: true, message: '请输入保质期!' }]
        },
        accessories: {
          rules: [{ required: true, message: '请输入附件!' }]
        },
        archiveFile: {
          rules: [{ required: true, message: '请上传归档文件!' }]
        },
        archived: {
          rules: [{ required: true, message: '请选择归档状态!' }]
        },
        signDate: {
          rules: [{ required: true, message: '请输入签订日期!' }]
        }
      },
      refKeys: ['contractPurchasePayment'],
      tableKeys: ['contractPurchasePayment'],
      activeKey: 'contractPurchasePayment',
      // 付款计划
      contractPurchasePaymentTable: {
        loading: false,
        dataSource: [],
        columns: {
          1:[{
            title: '付款条件',
            key: 'payCondition',
            required: true,
            type: FormTypes.slot,
            slotName: 'payCondition',
            // dictCode: 'sex',
            width: '60%',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
            {
              title: '计划付款金额（元）',
              required: true,
              key: 'expectMoney',
              width: '20%',
              type: FormTypes.inputNumber,
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '计划付款时间',
              required: true,
              key: 'expectTime',
              width: '20%',
              type: FormTypes.date,
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },],
          2:[
            {
              title: '付款条件',
              key: 'payCondition',
              required: true,
              type: FormTypes.slot,
              slotName: 'payCondition',
              // dictCode: 'sex',
              width: '40%',
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '计划付款金额（元）',
              required: true,
              key: 'expectMoney',
              width: '20%',
              type: FormTypes.inputNumber,
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '计划付款时间',
              required: true,
              key: 'expectTime',
              width: '20%',
              type: FormTypes.date,
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '实际付款金额（元）',
              required: true,
              key: 'actualMoney',
              width: '20%',
              type: FormTypes.inputNumber,
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '实际付款时间',
              required: true,
              key: 'actualTime',
              width: '20%',
              type: FormTypes.date,
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }]
            },
            {
              title: '付款完成',
              key: 'paymentCompleted',
              type: FormTypes.hidden,
              dictCode: 'switch_status'
            },
            {
              title: '是否开票',
              key: 'billing',
              type: FormTypes.hidden
            },
            {
              title: '开票比例',
              key: 'billingRatio',
              type: FormTypes.hidden
            },
            {
              title: '流程状态',
              key: 'bpmStatus',
              type: FormTypes.hidden
            }

          ]
        }
      },
      url: {
        add: '/contract/contractPurchase/add',
        edit: '/contract/contractPurchase/edit',
        queryById: '/contract/contractPurchase/queryById',
        contractPurchasePayment: {
          list: '/contract/contractPurchase/queryContractPurchasePaymentByMainId'
        }
      },
      fields: [
        'saleId',
        'saleNum',
        'saleName',
        'salesman',
        'num',
        'type',
        'name',
        'paymentMethod',
        'money',
        'qualityGuaranteePeriod',
        'accessories',
        'supplierId',
        'supplierName',
        'bpmStatus',
        'remarks',
        'projectId',
        'projectCode',
        'projectName',
        'archiveFile',
        'archived',
        'signDate',
        'charger',
        'customerName'
      ]
    }
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：false流程表单 true普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  watch: {
    '$store.state.bpm.bpmSubmitStates': {
      immediate: true,
      handler(val) {
        if (val && val.edit && val.edit === '1') {
          this.handleOk().then(res => {
            if (res) {
              this.$store.commit('BPM_SUBMIT_STATES', { edit: '2' })
            }
          })
        }
      }
    }
  },
  methods: {
    handleOk() {
      const that = this
      return new Promise(((resolve, reject) => {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          let url = this.url.add, method = 'post'
          if (this.model.id) {
            url = this.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(url, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              resolve(true)
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
          // return this.request(formData)
        }).catch(e => {
          this.$store.commit('BPM_SUBMIT_STATES', {})
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      }))

    },
    // validatorNum(rule,value,callback){
    //   if(value == 1){
    //     callback('不能输入1')
    //   }
    // },
    payConditionInputchange(event, props) {
      this.$nextTick(() => {
        let value = event.target.value
        let values = [
          {
            rowKey: props.getValue().id,
            values: {
              payCondition: value,
              expectMoney: props.getValue().expectMoney,
              expectTime: props.getValue().expectTime
            }
          }
        ]
        this.$refs.contractPurchasePayment.setValues(values)
      })
    },
    typeChange(value) {
      if (value == 1) {
        this.validatorRules.saleName.rules[0].required = true
      } else {
        this.validatorRules.saleName.rules[0].required = false
      }
    },
    addBefore() {
      this.form.resetFields()
      this.contractPurchasePaymentTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(this.model, this.fields)
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.contractPurchasePayment.list, params, this.contractPurchasePaymentTable)
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        contractPurchasePaymentList: allValues.tablesValue[0].values
      }
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    getFormFieldValue(field) {
      return this.form.getFieldValue(field)
    },
    saleNamePopupCallback(row) {
      this.saleId = row.saleId
      this.bidProjectId = row.bidProjectId
      this.form.setFieldsValue(pick(row, this.fields))
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, this.fields))
    },
    close() {
      this.saleId = null
      this.bidProjectId = null
    }
  }
}
</script>

<style scoped>
</style>